class_name ObjectPoolSystem
extends BaseSystem

#region 属性
@export var groups:Array[ObjectPoolGroup]
var item_dict:Dictionary
var obj_dict:Dictionary
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init_system(args = null):
	super(args)
	item_dict = {}
	obj_dict = {}
	for group in groups:
		group.fill_item_dict(item_dict)
#endregion
#region 公共方法
## 填充整个池子
func fill_pool():
	for item:ObjectPoolItem in item_dict.values():
		fill_single(item.id)
## 根据id填充单个
func fill_single(id:String):
	if item_dict.has(id):
		var objs:Array[Node] = item_dict[id].fill_pool()
		if objs.size() > 0:
			if not obj_dict.has(id):
				obj_dict[id] = []
			obj_dict[id].append_array(objs)
## 获取
func get_from_pool(id:String,count:int = 1):
	if count == 1:
		return get_single_from_pool(id)
	var objs = []
	if count > 0:
		for i in range(count):
			var obj = get_single_from_pool(id)
			if obj:
				objs.append(obj)
	return objs
## 放回
func put_to_pool(id:String,obj):
	if obj is Node:
		put_single_to_pool(id,obj)
	elif obj is Array[Node]:
		for o in obj:
			put_single_to_pool(id,o)
#endregion
#region 私有方法
## 获取一个
func get_single_from_pool(id:String):
	if not obj_dict.has(id):
		return null
	if obj_dict[id].size() == 0:
		fill_single(id)
	if obj_dict[id].size() == 0:
		return null
	var obj = obj_dict[id].pop_front()
	GameObjectPoolSystem.remove_child(obj)
	if "visible" in obj:
		obj.visible = true
	var o:ObjectPoolObj = Utils.find_child_by_type(obj,ObjectPoolObj,1)
	if o:
		o.get_from_pool()
	return obj
## 放回一个 TODO 未来可能需要优化，长时间不用的需要再销毁掉
func put_single_to_pool(id:String,obj:Node):
	if not obj_dict.has(id):
		return
	obj_dict[id].push_back(obj)
	if "visible" in obj:
		obj.visible = false
	var o:ObjectPoolObj = Utils.find_child_by_type(obj,ObjectPoolObj,1)
	if o:
		o.put_to_pool()
	if o.get_parent():
		o.get_parent().remove_child(o)
	GameObjectPoolSystem.add_child(obj)
#endregion
#region 生命周期函数
#endregion
